package com.hspedu.qqserver.service;

import com.hspedu.qqcommon.Message;
import com.hspedu.qqcommon.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 王先锋
 * @version 1.0
 * 该类对一个对象和某个客户端保持通讯
 */
public class ServerConnectClientThread extends Thread {
    private Socket socket;
    private String userId;//连接到服务器端的用户id

    public ServerConnectClientThread(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public void run() {//这里线程处于run状态，可以发送/接收消息
        while (true) {
            System.out.println("服务端和客户端保持通讯" + userId + "读取数据...");
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                //线程阻塞
                Message message = (Message) ois.readObject();
                //根据message类型，做相应业务
                if (message.getMesType().equals(MessageType.MESSAGE_GET_ONLINE_FRIEND)) {
                    //客户端要的再行列表
                    System.out.println(message.getSender() + "要在线列表");
                    String onlineUser = ManageClientThreads.getOnlineUser();
                    //返回message
                    //构建一个messag对象，返回客户端
                    Message message2 = new Message();
                    message2.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
                    message2.setContent(onlineUser);
                    message2.setGetter(message.getSender());
                    //写入到客户端
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(message2);

                } else if (message.getMesType().equals(MessageType.MESSAGE_CLIENT_EXIT)) {//客户端退出
                    System.out.println(message.getSender() + "退出");
                    //将客户端对应的线程，从集合中移除
                    ManageClientThreads.removeServerConnectClientThread(message.getSender());
                    //socket关闭
                    socket.close();
                    //退出线程
                    break;
                } else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {//指定用户发送消息
                    //根据message获取的getterid，然后得到响应线程，转发
                    ServerConnectClientThread serverConnectClientThread = ManageClientThreads.getServerConnectClientThread(message.getGetter());
                    ArrayList<Message> messages = new ArrayList<>();
                    ConcurrentHashMap<String, ArrayList<Message>> offLineDb=new ConcurrentHashMap<>();
                    if(serverConnectClientThread==null){
                        messages.add(message);
                        offLineDb.put(message.getGetter(),messages);
                        QQServer.setOffLineDb(offLineDb);
                    }else{
                    //得到对应socket的对象输出流，将message对象转发给指定客户端
                    ObjectOutputStream oos = new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                    oos.writeObject(message);//如果客户不在线，可以保存到数据库
                    }

                } else if (message.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)) {//群发消息
                    //需要遍历管理线程的集合，把所有的线程的socket得到，然后把message进行妆发
                    HashMap<String, ServerConnectClientThread> hm = ManageClientThreads.getHm();
                    Iterator<String> iterator = hm.keySet().iterator();
                    while (iterator.hasNext()) {
                        //取出在线用户ID
                        String onLineUserId = iterator.next().toString();
                        if (!onLineUserId.equals(message.getSender())) {//排除群发消息的用户
                            //进行转发
                            ObjectOutputStream oos = new ObjectOutputStream(hm.get(onLineUserId).socket.getOutputStream());

                            //转发
                            oos.writeObject(message);

                        }
                    }

                } else if (message.getMesType().equals(MessageType.MESSAGE_FILE_MES)) {//发送文件
                    //根据getterid获取到相应的线程，将message对象转发
                   ServerConnectClientThread  serverConnectClientThread=ManageClientThreads.getServerConnectClientThread(message.getGetter());
                    ObjectOutputStream oos = new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());

                    //转发
                    oos.writeObject(message);

                } else {
                    System.out.println("其他类型暂时不处理");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
